import { InjectionKey } from "vue";
import { createStore, Store, useStore as baseUseStore } from "vuex";
import { AllState, RootState } from "./types";
import userModule from "./modules/user/index";
import { RoleMenuVO } from "@/pojo/RoleMenuVO";

export default createStore<RootState>({
  state: {
    shownNavMenus: [],
  },
  mutations: {
    setShownNavMenus(state, payload: RoleMenuVO[]) {
      let shownNavMenus: Record<any, any> = {};
      payload.forEach((item) => {
        if (shownNavMenus[item.moduleId]) {
          shownNavMenus[item.moduleId].menus.push({
            url: item.url,
            name: item.name,
            id: item.id,
          });
        } else {
          shownNavMenus[item.moduleId] = {
            moduleId: item.moduleId,
            moduleName: item.moduleName,
            slug: item.slug,
            menus: [
              {
                url: item.url,
                name: item.name,
                id: item.id,
              },
            ],
          };
        }
      });

      state.shownNavMenus = Object.values(shownNavMenus);
    },
  },
  modules: {
    userModule,
  },
});

export const key: InjectionKey<Store<RootState>> = Symbol("store");

export function useStore<T = AllState>() {
  return baseUseStore<T>(key);
}
